<%--
  -	Date: 2012-05-25
  -
  - Copyright (C) 2012 Jawa Software. All rights reserved.
  - 
  - 创建新用户页面。
--%>
<%@page import="org.springframework.web.context.support.WebApplicationContextUtils"%>
<%@page import="org.springframework.context.ApplicationContext"%>
<%@ page language="java" pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c"%>
<%@ page import="org.jawa.learning.webapp.util.ParamUtils,org.jawa.core.util.JawaGlobals,org.jawa.core.JawaServer,org.jawa.learning.model.User,org.jawa.learning.service.UserManager,org.jawa.learning.model.Branch,org.jawa.core.database.SequenceManager,org.jawa.core.util.JawaConstants"
%>
<%@ page import="java.util.Collection,java.util.List,java.util.ArrayList,java.util.Map,java.util.HashMap,java.net.URLEncoder"
%>
<%@ page import="org.apache.commons.lang.StringUtils"%>
<jsp:useBean id="webManager" class="org.jawa.learning.webapp.util.WebManager" />
<% 
    webManager.init(request, response, session, application, out);
	String path = request.getContextPath();
%>

<%
	ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(session.getServletContext());
	UserManager userManager = (UserManager) ctx.getBean("userManager");
	Map<String,String> errors = new HashMap<String,String>();
	boolean success;
	
	boolean edit = request.getParameter("edit") != null;
	boolean create = request.getParameter("create") != null;
	boolean update = request.getParameter("update") != null;
	boolean delete = request.getParameter("delete") != null;
	
	Long userId = ParamUtils.getLongParameter(request,"userId",-1L);
	User user = null;
	if(edit){
		try{
			user = userManager.get(userId);
		}catch(Exception ex){
			//忽略
		}
	}
	if(null==user){
		user = new User();
	}
	
	if (delete)
	{
		userManager.remove(userId) ;
		success = true;
		response.sendRedirect("index.jsp?delete=true&success=true");
        return;
	}
	
	
	//创建用户
	if (create)
	{
		String username = ParamUtils.getParameter(request,"username");
		String fullName = ParamUtils.getParameter(request,"fullName");
		String userType = ParamUtils.getParameter(request,"userType");
		String enabled = ParamUtils.getParameter(request,"enabled");

		String sex = ParamUtils.getParameter(request,"sex");
		String phoneNumber = ParamUtils.getParameter(request,"phoneNumber");
		String email = ParamUtils.getParameter(request,"email");
		String picture = ParamUtils.getParameter(request,"picture");
		
		if(StringUtils.isEmpty(username)){
			errors.put("username","");
		}
		if(StringUtils.isEmpty(fullName)){
			errors.put("fullName","");
		}
		if(StringUtils.isEmpty(userType)){
			errors.put("userType","");
		}
		if(StringUtils.isEmpty(enabled)){
			errors.put("enabled","");
		}
		
		if(errors.isEmpty()){
			user = new User();
			user.setUsername(username);
			user.setFullName(fullName);
			user.setUserType(userType);
			user.setEnabled(enabled);
			user.setSex(sex);
			user.setPhoneNumber(phoneNumber);
			user.setEmail(email);
			user.setPicture(picture);
			try{
				Long nextUserId = SequenceManager.nextID(JawaConstants.DB_USER_SEQ);
				user.setId(nextUserId);
				user.setPassword(JawaConstants.USER_PASSWORD);
				userManager.saveUser(user);
				success = true;
			}catch(Exception ex){
				success = false;
				errors.put("create-general","");
			}
			
			if(success){
	            response.sendRedirect("index.jsp?create=true&success=true");
	            return;
			}
			
		}
	}
	
	if (update)
	{
		String userName = ParamUtils.getParameter(request,"username");
		String fullName = ParamUtils.getParameter(request,"fullName");
		String userType = ParamUtils.getParameter(request,"userType");
		String enabled = ParamUtils.getParameter(request,"enabled");

		String sex = ParamUtils.getParameter(request,"sex");
		String phoneNumber = ParamUtils.getParameter(request,"phoneNumber");
		String email = ParamUtils.getParameter(request,"email");
		String picture = ParamUtils.getParameter(request,"picture");
		
		if(StringUtils.isEmpty(userName)){
			errors.put("userName","");
		}
		if(StringUtils.isEmpty(userName)){
			errors.put("fullName","");
		}
		if(StringUtils.isEmpty(userType)){
			errors.put("userType","");
		}
		if(StringUtils.isEmpty(enabled)){
			errors.put("enabled","");
		}
		
		if(errors.isEmpty()){
			try{
				user = new User();
				user.setId(userId);
				user.setUsername(userName);
				user.setFullName(fullName);
				user.setUserType(userType);
				user.setEnabled(enabled);
				user.setSex(sex);
				user.setPhoneNumber(phoneNumber);
				user.setEmail(email);
				user.setPicture(picture);
				userManager.updateUser(user);
				success = true;
			}catch(Exception ex){
				success = false;
				errors.put("update-general","");
			}
			
			if(success){
	            response.sendRedirect("index.jsp?update=true&success=true");
	            return;
			}
			
		}
	}

%>
<!DOCTYPE html>
<html lang="en">
	<head>
		<title>创建新用户</title>
		<meta name="navID" content="1000" />
		<meta name="pageID" content="1301" />
		<meta name="hideSide" content="true" />
		<link rel="stylesheet"  href="<%= path %>/styles/uploadify.css">
		<style type="text/css">
		    .uploadify-button {
		        background-color: transparent;
		        border: none;
		        padding: 0;
		    }
		    .uploadify:hover .uploadify-button {
		        background-color: transparent;
		    }
		</style>
	</head>
	<body>
		<div class="container-fluid well">

			<%
				if(errors.get("create-general")!=null)
				{
			%>		
				  <div class="alert alert-error fade in">
				    <a class="close" data-dismiss="alert" href="#">×</a>
					<strong>创建用户时发生错误,可能是用户编号已存在.</strong>
				  </div>			
			<%	
				}
			%>
			<%
				if(errors.get("update-general")!=null)
				{
			%>		
				  <div class="alert alert-error fade in">
				    <a class="close" data-dismiss="alert" href="#">×</a>
					<strong>更新用户时发生错误.</strong>
				  </div>			
			<%	
				}
			%>
			<form id="userForm" action="user-form.jsp" method="post" class="form-horizontal ">
			    <%
			    	if(edit){
			    %>
			    	<input type="hidden" name="userId" value="<%=user.getId() %>">
			    <%		
			    	}
			    %>
				<fieldset>
					<legend>
						创建用户
					</legend>
					<div class="row-fluid">
						<div class="span8">
							<div class="control-group">
								<label class="control-label">
									用户名:
								</label>
								<div class="controls">
									<input type="text" name="username" value="<%=StringUtils.trimToEmpty(user.getUsername()) %>"  maxlength="15"  class="" />
									<%
										if (errors.get("username") != null) {
									%>
									<span class="help-inline">请输入用户编号</span>
									<%
										}
									%>
								</div>
							</div>
							<div class="control-group">
								<label class="control-label">
									用户姓名:
								</label>
								<div class="controls">
									<input type="text" name="fullName" value="<%=StringUtils.trimToEmpty(user.getFullName()) %>" maxlength="15"  class="" />
									<%
										if (errors.get("fullName") != null) {
									%>
									<span class="help-inline">请输入用户姓名</span>
									<%
										}
									%>									
								</div>
							</div>
							<div class="control-group">
								<label class="control-label">
									用户类型:
								</label>
								<div class="controls">
									<select id="userType" name="userType">
										<option value="1" <%=StringUtils.equals(user.getUserType(),"1")?"selected=\"selected\"":"" %> >
											用户
										</option>
										<option value="2" <%=StringUtils.equals(user.getUserType(),"2")?"selected=\"selected\"":"" %>>
											管理人员
										</option>
									</select>
									<%
										if (errors.get("userType") != null) {
									%>
									<span class="help-inline">请选择用户类型</span>
									<%
										}
									%>
								</div>
							</div>
							<div class="control-group">
								<label class="control-label">
									用户状态:
								</label>
								<div class="controls">
									<select id="enabled" name="enabled" >
										<option value="1" <%=StringUtils.equals(user.getEnabled(),"1")?"selected=\"selected\"":"" %>>
											正常
										</option>
										<option value="2" <%=StringUtils.equals(user.getEnabled(),"2")?"selected=\"selected\"":"" %>>
											失效
										</option>
									</select>
									<%
										if (errors.get("enabled") != null) {
									%>
									<span class="help-inline">请选择用户状态</span>
									<%
										}
									%>
								</div>
							</div>
							<div class="control-group">
								<label class="control-label">
									用户性别:
								</label>
								<div class="controls">
									<select id="sex" name="sex" >
										<option value="1" <%=StringUtils.equals(user.getSex(),"1")?"selected=\"selected\"":"" %>>
											男
										</option>
										<option value="2" <%=StringUtils.equals(user.getSex(),"2")?"selected=\"selected\"":"" %>>
											女
										</option>
									</select>
									<span class="help-inline"></span>
								</div>
							</div>
							<div class="control-group">
								<label class="control-label">
									联系电话:
								</label>
								<div class="controls">
									<input type="text" name="phoneNumber" value="<%=StringUtils.trimToEmpty(user.getPhoneNumber()) %>"  class="" />
									<span class="help-inline"></span>
								</div>
							</div>
							<div class="control-group">
								<label class="control-label">
									电子邮件:
								</label>
								<div class="controls">
									<input  type="text" name="email" value="<%=StringUtils.trimToEmpty(user.getEmail()) %>" class="">
								</div>
							</div>
						</div>
						
						<div class="span4">
							<ul class="thumbnails">
								<li class="span10">
									<div class="thumbnail">
										<img id="userPic" src="<%=path %>/images/260x180.gif" alt="" style="width:260px;height: 180px;">
										<input type="hidden" name="picture" id="user_picture" value=""/>
										<div class="caption">
											<h5>
												照片信息
											</h5>
											<div class="btn-group">
												<a id="upload_pic_btn" href="#" class="btn btn-primary">上传</a>
											</div>
										</div>
									</div>
								</li>
							</ul>
						</div>
						
						<div class="span12">
							<div class=" form-actions">
							    <%
							    	if(edit){
							    %>
							    	<input type="submit" name="update" value="保存用户" class="btn btn-primary"">
							    <%		
							    	}else{
								%>
									<input type="submit" name="create" value="保存用户" class="btn btn-primary" />
								<%							    		
							    	}
							    %>
								<input type="button" name="return" value="返回" class="btn" onclick="window.location.href='index.jsp'" />
							</div>
						</div>
					</div>
				</fieldset>
			</form>


		</div>
		<script src="<%= path %>/scripts/jquery-plugin/jquery.uploadify.js"></script>
		<script src="<%= path %>/scripts/jquery-plugin/jquery.validate.js"></script>
		<script src="<%= path %>/scripts/global.js"></script>
		<script>

		   $().ready(function() {
				$("#upload_pic_btn").uploadify({
					fileTypeExts : '*.gif; *.jpg; *.png',
				    formData      : {'reName' : 'true','uploadDir':'userpic'},
					height		  : 30,
					buttonImage   : '<%=path%>/images/browse-btn.png',
					swf			  : '<%=path%>/scripts/uploadify.swf',
					uploader:     '<%=path%>/ajaxFileUpload',
					width	      : 120,
			        onUploadSuccess : function(file, data, response) {
					    $("#userPic").attr("src",'<%=path%>/'+data); 
					    $("#user_picture").val('<%=path%>/'+data); 
					}
				});
			
				$("#userForm").validate({
					rules: {
						username: {
							required  : true,
							minlength : 2
						},
						fullName: {
							required  : true,
							minlength : 2
						},
						userType: {
							required  : true
						},
						enabled: {
							required  : true
						},
						sex: {
							required  : true
						},
						phoneNumber: {
							minlength : 7,
							minlength : 20
						},
						email: {
							email : true
						}
					},
					
					messages: {
					}
				});	
						
			});
		</script>
		
	</body>